<?php
declare (strict_types = 1);

namespace app\common\command\make;

use think\console\command\Make;
use think\console\input\Argument;
use think\facade\Db;

class Request extends Make
{
    protected $type="Request";
    protected $data;


    protected function configure()
    {
        // 指令配置
        parent::configure();
        $this->setName('make:request')
            ->addArgument('connection',Argument::REQUIRED,'this table connection')
            ->addArgument('table',Argument::REQUIRED,'this table name')
            ->setDescription('the request command');
    }

    protected function getStub(): string
    {
        return __DIR__ . DIRECTORY_SEPARATOR . 'stubs' . DIRECTORY_SEPARATOR . 'request.stub';
    }

    protected function getNamespace(string $app): string
    {
        return parent::getNamespace($app) . '\\request';
    }

    protected function buildClass(string $name)
    {
        $stub = file_get_contents($this->getStub());

        $namespace = trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');

        $class = str_replace($namespace . '\\', '', $name);

        return str_replace(['{%className%}', '{%actionSuffix%}', '{%namespace%}', '{%app_namespace%}','{%rule%}','{%message%}','{%scene%}'], [
            $class,
            $this->app->config->get('route.action_suffix'),
            $namespace,
            $this->app->getNamespace(),
            $this->rule(),
            $this->message(),
            $this->scene(),
        ], $stub);
    }

    protected function rule()
    {
        // 指令输出
        $link=$this->input->getArgument('connection');
        $table=$this->input->getArgument('table');

        $result=Db::connect($link)->query('SHOW FULL COLUMNS FROM '.$table);
        $rule='';
        foreach ($result as $item) {
            $val = array_change_key_case($item);
            $rule .="'{$val['field']}'=> 'require',\n";
        }
        return rtrim($rule);
    }

    protected function message()
    {
        // 指令输出
        $link=$this->input->getArgument('connection');
        $table=$this->input->getArgument('table');

        $result=Db::connect($link)->query('SHOW FULL COLUMNS FROM '.$table);
        $message='';
        foreach ($result as $item) {
            $val = array_change_key_case($item);
            $message .="'{$val['field']}.require'=> '{$val['field']}',\n";
        }
        return rtrim($message);
    }

    protected function scene()
    {
        // 指令输出
        $link=$this->input->getArgument('connection');
        $table=$this->input->getArgument('table');

        $result=Db::connect($link)->query('SHOW FULL COLUMNS FROM '.$table);
        $scene='';
        foreach ($result as $item) {
            $val = array_change_key_case($item);
            $scene .="'{$val['field']}',";
        }
        return rtrim($scene,',');
    }

}
